package com.digitalchina.lxnsy.fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.digitalchina.lxnsy.R;
import com.digitalchina.lxnsy.activity.old.ExpertsDetailActivity;
import com.digitalchina.lxnsy.activity.old.PlantExpertListActivity;
import com.digitalchina.lxnsy.activity.old.PlantProductionDetailActivity;
import com.digitalchina.lxnsy.activity.old.StandardProductionDetailActivity;
import com.digitalchina.lxnsy.activity.old.TechnologyTrainingVideoDetailNewActivity;
import com.digitalchina.lxnsy.activity.old.WebViewActivity;
import com.digitalchina.lxnsy.api.BusinessPlan;
import com.digitalchina.lxnsy.base.BaseV4Fragment;
import com.digitalchina.lxnsy.constant.MSG;
import com.digitalchina.lxnsy.constant.URL;
import com.digitalchina.lxnsy.entity.ExpertNewVO;
import com.digitalchina.lxnsy.entity.PlanProductVO;
import com.digitalchina.lxnsy.entity.PlanVoSimpleVO;
import com.digitalchina.lxnsy.entity.ProductStandardVO;
import com.digitalchina.lxnsy.entity.WeatherVO;
import com.digitalchina.lxnsy.toolkit.DateStyle;
import com.digitalchina.lxnsy.toolkit.DateUtil;
import com.digitalchina.lxnsy.toolkit.FastJsonUtil;
import com.digitalchina.lxnsy.toolkit.FrescoUtil;
import com.digitalchina.lxnsy.toolkit.GotoUtil;
import com.digitalchina.lxnsy.toolkit.SharedPreferencesUtil;
import com.digitalchina.lxnsy.toolkit.StringUtil;
import com.digitalchina.lxnsy.toolkit.Utils;
import com.digitalchina.lxnsy.widget.VerticalTextview;
import com.digitalchina.lxnsy.xml.UserXML;
import com.facebook.drawee.view.SimpleDraweeView;
import com.hedgehog.ratingbar.RatingBar;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static android.app.Activity.RESULT_OK;

/**
 * ================================================
 * 项目名称：BigData
 * 类描述：
 * 包名：com.digitalchina.bigdata.fragment
 * 创建人：郑皓
 * 创建时间：2018/8/23 15:25
 * 修改备注：
 * ================================================
 */
public class PlantToadyRecommendFragment extends BaseV4Fragment {
    @Bind(R.id.tv_date)
    TextView tvDate;
    @Bind(R.id.tv_today_farming)
    TextView tvTodayFarming;
    @Bind(R.id.tv_content)
    TextView tvContent;
    @Bind(R.id.recyclerView1)
    RecyclerView recyclerView1;
    @Bind(R.id.tv_city)
    TextView tvCity;
    @Bind(R.id.tv_temperature)
    TextView tvTemperature;
    @Bind(R.id.tv_wind)
    TextView tvWind;
    @Bind(R.id.tv_weather)
    TextView tvWeather;
    @Bind(R.id.product_detail_tv_message)
    TextView productDetailTvMessage;
    @Bind(R.id.recyclerView2)
    RecyclerView recyclerView2;
    @Bind(R.id.sdv_weather)
    SimpleDraweeView sdvWeather;
    @Bind(R.id.tv_detail)
    TextView tvDetail;
    @Bind(R.id.tv_video)
    TextView tvVideo;
    @Bind(R.id.tv_tips)
    VerticalTextview tvTips;
    @Bind(R.id.layout_tips)
    LinearLayout layoutTips;
    @Bind(R.id.tv_tips_null)
    TextView tvTipsNull;
    @Bind(R.id.tv_tel)
    TextView tvTel;
    @Bind(R.id.layout_tel)
    RelativeLayout layoutTel;

    private List<ProductStandardVO.StandardMsgListBean> standardMsgList;


    private List<ExpertNewVO> expertList = new ArrayList<>();
    private PlanProductVO.FarmOperationBean farmOperation;
    private List<WeatherVO> voList = new ArrayList<>();

    private ExpertRecyclerAdapter expertRecyclerAdapter;
    private WeatherRecyclerAdapter weatherRecyclerAdapter;

    private Map<String, String> map = new HashMap<>();

    private String productStandardId = "";

    private String planId = "";

    private String operationCompleted = ""; // 1为当前农事操作已经完成到最后一步

    @Override
    public View setRootView() {
        return inflate(R.layout.fragment_toady_recommend);
    }

    @Override
    public void initMember() {

//        String city = getArguments().getString("city");
        planId = getArguments().getString("planId");

//        BusinessPlan.getCityWeatherList(getActivity(), city, mHandler);
        BusinessPlan.todayRecommend(getActivity(), planId, mHandler);


        recyclerView1.setLayoutManager(new LinearLayoutManager(getActivity()));

        recyclerView1.setHasFixedSize(true);
        recyclerView1.setNestedScrollingEnabled(false);
        recyclerView1.setFocusable(false);


        recyclerView2.setLayoutManager(new LinearLayoutManager(getActivity()));

        recyclerView2.setHasFixedSize(true);
        recyclerView2.setNestedScrollingEnabled(false);
        recyclerView2.setFocusable(false);


        tvDate.setText(DateUtil.getCurrentDate(DateStyle.YYYY_MM_DD));

        expertRecyclerAdapter = new ExpertRecyclerAdapter(expertList);
        recyclerView1.setAdapter(expertRecyclerAdapter);

        weatherRecyclerAdapter = new WeatherRecyclerAdapter(voList);
        recyclerView2.setAdapter(weatherRecyclerAdapter);


    }

    @Override
    public void addListener() {

        expertRecyclerAdapter.setOnItemClickListener(new ExpertRecyclerAdapter.OnItemClickListener() {

            @Override
            public void onItemClick(int position) {
                Map<String, Object> map = new HashMap<>();
                map.put("ExpertVO", expertList.get(position));

                GotoUtil.gotoActivity(getActivity(), ExpertsDetailActivity.class, "map", map);
            }
        });

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK)
            BusinessPlan.todayRecommend(getActivity(), planId, mHandler);
    }

    @Override
    public void setHandler() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);

                if (getActivity() == null || getActivity().isFinishing())
                    return;

                switch (msg.what) {
                    case MSG.MSG_TODAY_RECOMMEND_SUCCESS:
                        callBack(msg.obj);
                        break;
                    case MSG.MSG_GET_CITY_7DAYS_WEATHER_SUCCESS:
                        voList = FastJsonUtil.getListBean(msg.obj.toString(), "cityWeatherSimList", WeatherVO.class);
                        weatherRecyclerAdapter.setData(voList);

                        if (voList != null && voList.size() > 0) {

                            tvCity.setText(voList.get(0).getCity());
                            tvTemperature.setText(voList.get(0).getTemplow() + "~" + voList.get(0).getTemphigh() + " ℃");
                            tvWeather.setText(voList.get(0).getWeather() + "");
                            SharedPreferencesUtil.setValue(getActivity(), UserXML.XML_NAME_USER, "curWeather", voList.get(0).getTemplow() + "~" + voList.get(0).getTemphigh() + "℃ " + voList.get(0).getWeather());
                            if (!StringUtil.isStrEmpty(voList.get(0).getImg())) {
                                sdvWeather.setVisibility(View.VISIBLE);
                                FrescoUtil.showImageForURL(URL.SERVER + voList.get(0).getImg().substring(1, voList.get(0).getImg().length()), sdvWeather);
                            }
                        } else {
                            tvCity.setText("");
                            tvTemperature.setText("");
                            tvWeather.setText("");
                            sdvWeather.setVisibility(View.INVISIBLE);
                        }

                        break;
                    case MSG.MSG_TODAY_RECOMMEND_FIELD:
                        showToast(msg.obj.toString());
                        break;
                }
            }
        };
    }

    @Override
    public void callBack(Object object) {

        PlanVoSimpleVO planVo = FastJsonUtil.getBean(object.toString(), "planVo", PlanVoSimpleVO.class);
//        planVo.setSeedDate(FastJsonUtil.getString(object.toString(), "seedDate"));
//        planVo.setCropName(FastJsonUtil.getString(object.toString(), "cropName"));

        StandardProductionDetailActivity activity = (StandardProductionDetailActivity) getActivity();
        if (planVo != null) {
            activity.setTopView(planVo.getIsFree(), planVo.getLeaveValidDay());
        }


        expertList = FastJsonUtil.getListBean(object.toString(), "expertInfos", ExpertNewVO.class);
        standardMsgList = FastJsonUtil.getListBean(object.toString(), "standardMsgList", ProductStandardVO.StandardMsgListBean.class);
        farmOperation = FastJsonUtil.getBean(object.toString(), "farmOperation", PlanProductVO.FarmOperationBean.class);
        productStandardId = FastJsonUtil.getString(object.toString(), "productStandardId");
        operationCompleted = FastJsonUtil.getString(object.toString(), "operationCompleted");
        String consultationHotline = FastJsonUtil.getString(object.toString(), "consultationHotline");
        String productStandardfeeType = FastJsonUtil.getString(object.toString(), "productStandardfeeType");

        // 联系电话  付费用户展示
        if ("1".equals(productStandardfeeType)) {
            tvTel.setText(consultationHotline);
            layoutTel.setVisibility(View.VISIBLE);
        } else {
            layoutTel.setVisibility(View.GONE);
        }


        SharedPreferencesUtil.setValue(getActivity(), UserXML.XML_NAME_USER, "productStandardId", productStandardId);

        expertRecyclerAdapter.setData(expertList);

        if (farmOperation != null)
            setView();


        String provinceName = FastJsonUtil.getString(object.toString(), "provinceName");
        String cityName = FastJsonUtil.getString(object.toString(), "cityName");
        String countyName = FastJsonUtil.getString(object.toString(), "countyName");

        if (!StringUtil.isStrEmpty(cityName) && !cityName.equals("县")) {
            BusinessPlan.getCityWeatherList(getActivity(), cityName, mHandler);
        } else {
//            if (!StringUtil.isStrEmpty(countyName)) {
//                BusinessPlan.getCityWeatherList(getActivity(), countyName, mHandler);
//            } else {
            BusinessPlan.getCityWeatherList(getActivity(), provinceName, mHandler);
//            }
        }

    }

    private void setView() {

        if (!operationCompleted.equals("1")) {
            tvDetail.setVisibility(View.VISIBLE);
            if (!StringUtil.isStrEmpty(farmOperation.getFarmName()))
                tvTodayFarming.setText(farmOperation.getFarmName());
            if (!StringUtil.isStrEmpty(farmOperation.getOperInstr()))
                tvContent.setText(farmOperation.getOperInstr());
            if (!StringUtil.isStrEmpty(farmOperation.getVidAddress()))
                tvVideo.setVisibility(View.VISIBLE);
        } else {
            tvTodayFarming.setText("已完成");
            tvContent.setText("您的作物标准种植已结束，可以出售啦。");
            tvDetail.setVisibility(View.INVISIBLE);
            tvVideo.setVisibility(View.GONE);
        }

        ArrayList<String> titleList = new ArrayList<>();
        if (standardMsgList != null && standardMsgList.size() > 0) {
            tvTips.removeAllViews();
            tvTips.removeAllViewsInLayout();
            tvTips.setVisibility(View.VISIBLE);
            tvTipsNull.setVisibility(View.GONE);
            for (int i = 0; i < standardMsgList.size(); i++) {
                titleList.add(standardMsgList.get(i).getTitle());
            }

            tvTips.setTextList(titleList);
            tvTips.setText(12, 0, getContext().getResources().getColor(R.color.colorWhite));//设置属性
            tvTips.setTextStillTime(3000);//设置停留时长间隔
            tvTips.setAnimTime(300);//设置进入和退出的时间间隔
            tvTips.setOnItemClickListener(new VerticalTextview.OnItemClickListener() {
                @Override
                public void onItemClick(int position) {
                    map.put("title", standardMsgList.get(position).getTitle());
                    map.put("url", standardMsgList.get(position).getUrl());
                    GotoUtil.gotoActivity((Activity) getContext(), WebViewActivity.class, "map", map);
                }
            });
            tvTips.startAutoScroll();
        } else {
            tvTips.setVisibility(View.GONE);
            tvTipsNull.setVisibility(View.VISIBLE);
        }

    }

    @Override
    public void rightOnClick() {

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @OnClick({R.id.layout_detail, R.id.layout_more, R.id.tv_video, R.id.tv_tel})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.layout_detail:
                if (!operationCompleted.equals("1"))
                    if (farmOperation != null) {
                        farmOperation.setPlanId(planId);
                        farmOperation.setProductStandardId(productStandardId);
                        farmOperation.setOperation(true);
                        Intent intent = new Intent(getActivity(), PlantProductionDetailActivity.class);
                        intent.putExtra("vo", (Serializable) farmOperation);
                        startActivityForResult(intent, 97);
                    }
                break;
            case R.id.layout_more:
                if (!StringUtil.isStrEmpty(productStandardId))
                    GotoUtil.gotoActivity(getActivity(), PlantExpertListActivity.class, "productStandardId", productStandardId);
                break;
            case R.id.tv_video:
                GotoUtil.gotoActivity(getActivity(), TechnologyTrainingVideoDetailNewActivity.class, "path", farmOperation.getVidAddress());
                break;
            case R.id.tv_tel:
                Utils.callPhone(getContext(), tvTel.getText().toString());
                break;
        }
    }

    // 获取今日推荐
    public void updatePlanId(String planId) {
        this.planId = planId;
        BusinessPlan.todayRecommend(getActivity(), planId, mHandler);
    }


    public static class ExpertRecyclerAdapter extends RecyclerView.Adapter<ExpertRecyclerAdapter.ViewHolder> {

        private List<ExpertNewVO> list;

        public ExpertRecyclerAdapter(List<ExpertNewVO> list) {
            this.list = list;
        }


        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_experts_detail, parent, false);
            return new ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(ViewHolder holder, final int position) {
            FrescoUtil.showImageSmall(list.get(position).getPhoto() != null ? list.get(position).getPhoto() : "", holder.ivImage);
            holder.tvExpertName.setText(list.get(position).getExpertName() != null ? list.get(position).getExpertName() : "");

            if (mOnItemClickListener != null)
                holder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mOnItemClickListener.onItemClick(position);
                    }
                });

            if (list.get(position).getExpertTitle() != null) {
                holder.title.setText(list.get(position).getExpertTitle().getTitle());
            } else
                holder.title.setVisibility(View.GONE);
//        tvExpertArea.setText(list.get(position).getExpertClassification() != null ? list.get(position).getExpertClassification().getPname() + "  " + list.get(position).getExpertClassification().getName() : "");
            if (list.get(position).getExpertAreas() != null) {
                StringBuilder s = new StringBuilder();
                for (int i = 0; i < list.get(position).getExpertAreas().size(); i++) {
                    s.append(list.get(position).getExpertAreas().get(i).getExpertAreaType().getName()).append("-").append(list.get(position).getExpertAreas().get(i).getExpertAreaDirection().getName()).append("\n");
                }
                holder.tvExpertArea.setText(s.toString());
            }
            holder.barScore.setStar((float) list.get(position).getScore());
        }

        public int getItemCount() {
            return list.size();
        }

        public void setData(List<ExpertNewVO> list) {
            this.list.clear();
            if (list != null)
                this.list = list;
            notifyDataSetChanged();
        }

        private OnItemClickListener mOnItemClickListener;//声明接口

        public interface OnItemClickListener {
            void onItemClick(int position);
        }

        public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
            this.mOnItemClickListener = onItemClickListener;
        }


        class ViewHolder extends RecyclerView.ViewHolder {
            TextView tvExpertName;
            TextView title;
            TextView tvExpertArea;
            RatingBar barScore;
            SimpleDraweeView ivImage;

            ViewHolder(View itemView) {
                super(itemView);
                ivImage = itemView.findViewById(R.id.item_iv_expert_iv_avatar);
                tvExpertName = itemView.findViewById(R.id.item_expert_list_tv_name);
                title = itemView.findViewById(R.id.item_expert_list_tv_titles);
                tvExpertArea = itemView.findViewById(R.id.item_expert_list_tv_area);
                barScore = itemView.findViewById(R.id.item_expert_list_bar_score);
            }
        }

    }


    public class WeatherRecyclerAdapter extends RecyclerView.Adapter<WeatherRecyclerAdapter.ViewHolder> {

        private List<WeatherVO> list;

        public WeatherRecyclerAdapter(List<WeatherVO> list) {
            this.list = list;
        }


        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_plan_weather, parent, false);
            return new ViewHolder(view);
        }


        @Override
        public void onBindViewHolder(ViewHolder holder, int position) {
            if (!StringUtil.isStrEmpty(list.get(position).getImg()))
                FrescoUtil.showImageForURL(URL.SERVER + list.get(position).getImg().substring(1, list.get(position).getImg().length()), holder.sdv);

            holder.tvT.setText(list.get(position).getTemplow() + "~" + list.get(position).getTemphigh() + " ℃");
            holder.tvWeather.setText(list.get(position).getWeather() + "");
            holder.tvDate.setText(list.get(position).getOneDay() + "");
        }

        @Override
        public int getItemCount() {
            return list.size();
        }

        public void setData(List<WeatherVO> list) {
            this.list.clear();
            if (list != null)
                this.list = list;
            notifyDataSetChanged();
        }


        class ViewHolder extends RecyclerView.ViewHolder {
            TextView tvDate;
            TextView tvWeather;
            TextView tvT;
            SimpleDraweeView sdv;

            ViewHolder(View itemView) {
                super(itemView);
                tvDate = itemView.findViewById(R.id.tv_date);
                tvWeather = itemView.findViewById(R.id.tv_weather);
                tvT = itemView.findViewById(R.id.tv_t);
                sdv = itemView.findViewById(R.id.sdv_weather);
            }
        }

    }
}
